﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;

namespace Chapter04
{
    public partial class Example106 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var word = "红尘倒影";
            var width = (int)Math.Ceiling(word.Length * 20.5);
            var height = 22;
            var verification = new Bitmap(width, height);
            var canvas = Graphics.FromImage(verification);

            try
            {
                var random = new Random();
                canvas.Clear(Color.White);

                for (int i = 0; i < 2; i++)
                {
                    var x1 = random.Next(verification.Width);
                    var x2 = random.Next(verification.Width);
                    var y1 = random.Next(verification.Height);
                    var y2 = random.Next(verification.Height);
                    canvas.DrawLine(new Pen(Color.Black), x1, y1, x2, y2);
                }

                var arial = new Font("Arial", 12, FontStyle.Bold);
                var blueToRedLinearBrush = new LinearGradientBrush(new Rectangle(0, 0, verification.Width, verification.Height), Color.Blue, Color.DarkRed, 1.2f, true);
                canvas.DrawString(word, arial, blueToRedLinearBrush, 2, 2);

                for (int i = 0; i < 100; i++)
                {
                    var x = random.Next(verification.Width);
                    var y = random.Next(verification.Height);
                    verification.SetPixel(x, y, Color.FromArgb(random.Next()));
                }
                canvas.DrawRectangle(new Pen(Color.Silver), 0, 0, verification.Width - 1, verification.Height - 1);

                var cache = new MemoryStream();
                verification.Save(cache, ImageFormat.Gif);

                Response.ClearContent();
                Response.ContentType = "image/gif";
                Response.BinaryWrite(cache.ToArray());
            }
            finally
            {
                canvas.Dispose();
                verification.Dispose();
            }
        }
    }
}